<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Good;
use DB;
class GoodsController extends Controller
{
    //吉祥物板块
	//吉祥物添加
    public function goods_list_add(Request $request,Good $good){
    	if($request->isMethod('post')){
    		    $data = $request->all();
    		    if(empty($request->file('img'))){
    		        $img = '';
                }else{
                    $img = $request->file('img')->store(date('Y-m-d'));
                }
    			$data['img'] = $img;
    			$data['content'] = $data['editorValue'];
    			//如果没有填写简介,截取文章前五十字
    			if (empty($data['tell'])) {
                    $tell = strip_tags($data['editorValue']);
                    $data['tell'] = mb_substr($tell, 0, 50, 'utf-8');
                }
    			$list = $good->create($data);
    			if($list != false && $list != null){
    				session()->flash('success', '保存成功！');
                    return redirect('admin/goods/goods_list_add');
    			}else{
    				session()->flash('success', '保存失败！');
                    return redirect('admin/goods/goods_list_add');
    			}
    	}else{
    		return view('Admin/goods/goods_list_add');
    	}
    }
    //吉祥物列表
    public function goods_list(){
    	$data = DB::select('select * from goods');
    	return view('Admin/goods/goods_list',['data' => $data]);
    }
    //吉祥物修改
    public function goods_upd(Good $good,$id){
    	$data = $good->where('id',$id)->get();
    	return view('Admin/goods/goods_upd',['data' => $data]);
    }
    //吉祥物修改
    //第一种方法  直接把数据全部给到另外一个
    public function update(Request $request,Good $good){
    	$data = $request->except('_token');
        $where = [ 'id' => $data['id']];
        if(!empty($data['editorValue'])){
            $re['content'] = $data['editorValue'];
        }
        if(!is_null($request->file('img'))){
                $re['img'] = $request->file('img')->store(date('Y-m-d'));
        }
        $re['title'] = $data['title'];
        $re['recomm'] = $data['recomm'];
        $re['id'] = $data['id'];
        $re['tell'] = $data['tell'];
        $result = $good->where($where)->update($re);
        if($result != false){
            session()->flash('success','修改成功');
            return redirect()->back();
        }else{
            session()->flash('success','修改失败');
            return redirect()->back();
        }
    }
    //删除
    public function delete(Good $good,$id){
    	$list = $good->where('id',$id)->delete();
    	return redirect()->back();
    }
}
